//
//  ChatTableViewVoiceCell.m
//  供销宝
//
//  Created by 金晶 on 17/2/14.
//  Copyright © 2017年 金晶. All rights reserved.
//

#import "ChatTableViewVoiceCell.h"
#import "VoiceChatModule.h"

@interface ChatTableViewVoiceCell ()

@property (nonatomic,strong) ChatMessage *ChatMessage;

@property (nonatomic,strong) UIImageView *pointView;

@property (nonatomic,strong) UILabel *voiceTimeLabel;

@property (nonatomic,weak)ChatTableView *chatTabview;

@end

@implementation ChatTableViewVoiceCell

- (void)dealloc {
    [[VoiceChatModule getInstance] stopPlayAudio];
    [NSNotificationCenter removeAllNotification:self];
}


+ (UITableViewCell *)cellWithTableView:(ChatTableView *)tableView messageModel:(ChatMessage *)model withmasTop:(CGFloat)masTop {
    
    static NSString *voiceCellIndentifier = @"voiceCellIndentifier";
    
    ChatTableViewVoiceCell *cell = [tableView dequeueReusableCellWithIdentifier:voiceCellIndentifier];
    
    if(!cell) {
        
        cell = [[ChatTableViewVoiceCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:voiceCellIndentifier];
    }
    
    cell.ChatMessage = model;
    cell.chatTabview = tableView;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if(model.msgSourceType==CHAT_MSG_RECV) {
        
        cell.logoImage.frame=CGRectMake(10, masTop, 40, 40);
        
        BOOL isShowNickName = NO;
        if ([tableView.chatProtocol.chatDelegate respondsToSelector:@selector(isShowNickName)]) {
            isShowNickName = [tableView.chatProtocol.chatDelegate isShowNickName];
        }
        
        if (isShowNickName) {
            cell.nickNameLabel.frame = CGRectMake(cell.logoImage.right+8, masTop, 150, [cell returnNameTop:isShowNickName]-3);
        }else{
            cell.nickNameLabel.frame = CGRectMake(cell.logoImage.right+8, masTop, 0, 0);
        }
        cell.nickNameLabel.textAlignment = NSTextAlignmentLeft;
        
        cell.contextBack.frame=CGRectMake(LEFT_WITH, masTop+[cell returnNameTop:isShowNickName], [cell voiceLength:[model.voiceLength integerValue]], 40);
        cell.contextBack.image=[[UIImage imageNamed:@"wechatback1"] stretchableImageWithLeftCapWidth:10 topCapHeight:25];
        
        cell.voiceAnimationImageView.frame=CGRectMake(12, 12, 12, 16);
        cell.voiceAnimationImageView.image=[UIImage imageNamed:@"wechatvoice3"];
        
        cell.voiceAnimationImageView.animationImages=[NSArray arrayWithObjects:[UIImage imageNamed:@"wechatvoice3"],[UIImage imageNamed:@"wechatvoice3_1"],[UIImage imageNamed:@"wechatvoice3_0"],[UIImage imageNamed:@"wechatvoice3_1"],[UIImage imageNamed:@"wechatvoice3"],nil];
        
        CGFloat pointView_X = cell.contextBack.frame.origin.x+cell.contextBack.frame.size.width+5;
        
        cell.voiceTimeLabel.frame =CGRectMake(pointView_X, masTop+[cell returnNameTop:cell.isShowName], 20, 40);
        cell.voiceTimeLabel.textAlignment = NSTextAlignmentLeft;
        cell.voiceTimeLabel.text = model.voiceLength;
        
        if(model.readStatus==CHAT_MSG_UNREAD) {
            
            cell.pointView.frame = CGRectMake(pointView_X, cell.contextBack.frame.origin.y, 8, 8);
            
            cell.pointView.hidden = NO;
        }else {
            cell.pointView.hidden = YES;
        }


    }else if(model.msgSourceType==CHAT_MSG_SEND) {

        cell.logoImage.frame=CGRectMake(kScreenWidth-10-40, masTop, 40, 40);
        
        BOOL isShowNickName = NO;
        if ([tableView.chatProtocol.chatDelegate respondsToSelector:@selector(isShowNickName)]) {
            isShowNickName = [tableView.chatProtocol.chatDelegate isShowNickName];
        }
        
        if (isShowNickName) {
            cell.nickNameLabel.frame = CGRectMake(cell.logoImage.left-150-8, masTop, 150, [cell returnNameTop:isShowNickName]-3);
        }else{
            cell.nickNameLabel.frame = CGRectMake(cell.logoImage.left-150-8, masTop, 0, 0);
        }
        cell.nickNameLabel.textAlignment = NSTextAlignmentRight;
        
        cell.contextBack.frame=CGRectMake(kScreenWidth-LEFT_WITH-[cell voiceLength:[model.voiceLength integerValue]], masTop+[cell returnNameTop:isShowNickName], [cell voiceLength:[model.voiceLength integerValue]], 40);
        cell.contextBack.image=[[UIImage imageNamed:@"wechatback2"] stretchableImageWithLeftCapWidth:10 topCapHeight:25];
        
        cell.voiceAnimationImageView.frame=CGRectMake([cell voiceLength:[model.voiceLength integerValue]]-12-11, 12, 11, 16);
        cell.voiceAnimationImageView.image=[UIImage imageNamed:@"wechatvoice4"];
        cell.voiceAnimationImageView.animationImages=[NSArray arrayWithObjects:[UIImage imageNamed:@"wechatvoice4"],[UIImage imageNamed:@"wechatvoice4_1"],[UIImage imageNamed:@"wechatvoice4_0"],[UIImage imageNamed:@"wechatvoice4_1"],[UIImage imageNamed:@"wechatvoice4"],nil];
        
        cell.voiceTimeLabel.frame =CGRectMake(cell.contextBack.frame.origin.x-23, masTop+[cell returnNameTop:cell.isShowName], 20, 40);
        cell.voiceTimeLabel.textAlignment = NSTextAlignmentRight;
        cell.voiceTimeLabel.text = model.voiceLength;
        
        cell.pointView.hidden = YES;
        
        //正在发送状态
        if(model.messageState == CHAT_MSG_SENDING){
            [cell.acview startAnimating];
            [cell.acview setHidden:NO];
            [cell.retryButton setHidden:YES];
            
            [cell.acview mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contextBack);
                make.right.mas_equalTo(cell.voiceTimeLabel.mas_left).offset(-10);
            }];
        } else if (model.messageState ==CHAT_MSG_SEND_NONE) {
            //未发送状态
            [cell.acview setHidden:YES];
            [cell.retryButton setHidden:NO];
            
            [cell.retryButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contextBack);
                make.right.mas_equalTo(cell.voiceTimeLabel.mas_left).offset(-10);
            }];
        }else {
            [cell.acview setHidden:YES];
            [cell.retryButton setHidden:YES];
        }
    }
        
    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    
    if(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [NSNotificationCenter addOneVoiceCellPlayerNotification:self action:@selector(oneVoiceCellPlayer:)];
        [NSNotificationCenter addAudioPlayDidFinishNotification:self action:@selector(audioPlayerDone:)];
    }
    return self;
}


- (UIImageView *)pointView {
    
    if(!_pointView) {
        
        _pointView = [[UIImageView alloc]init];
        _pointView.image = [UIImage imageNamed:@"redPoint"];
        [self.contentView addSubview:_pointView];
    }
    return _pointView;
}

- (UILabel *)voiceTimeLabel {
    
    if(!_voiceTimeLabel) {
        
        _voiceTimeLabel = [[UILabel alloc]init];
        _voiceTimeLabel.backgroundColor = [UIColor clearColor];
        _voiceTimeLabel.textColor = [UIColor grayColor];
        _voiceTimeLabel.font = [UIFont systemFontOfSize:10];
        [self.contentView addSubview:_voiceTimeLabel];
    }
    
    return _voiceTimeLabel;
}

//语音的长度
- (CGFloat)voiceLength:(NSInteger)seconds {
    
    if (seconds==0) {
        return 75;
    }
    
    //    6~197 6p~230
    // 75
    
    CGFloat max=kScreenWidth>750?230:197;
    
    return 75+(seconds-1)*(max-75)*1.0/60.0;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)startVoiceAnimation {
    
    [self.voiceAnimationImageView startAnimating];
}

- (void)stopVoiceAnimation {
    
    [self.voiceAnimationImageView stopAnimating];
}

/*  
   如果语音录制时，过大，还在放送中。点击是没有效果的。
   可以通过传输协议，来判断数据是否传输完
   点击播放的时放的时候，要记录当前的cell.
   如果有其它的语音在播放，要停止其它的播放，然后在播放当前点击的
 */
- (void)handleSingleTap:(UITapGestureRecognizer *)sender {
    
    CGPoint point = [sender locationInView:self.chatTabview];
    NSIndexPath *indexPath = [self.chatTabview indexPathForRowAtPoint:point];
    
    [self.voiceAnimationImageView setTag:indexPath.row];
    //修改已读未读状态
    [self modifierReadStatus:indexPath];
    
    //显示语音，判断是好友发送还是自己发送
    [self clickCell];
    
    !self.selectVoiceBlock?:self.selectVoiceBlock(indexPath);
}

//修改已读未读状态
- (void)modifierReadStatus:(NSIndexPath *)indexPath {
    self.ChatMessage.readStatus = CHAT_MSG_READED;
    [self.chatTabview.chatProtocol uploadMessageStatus:self.ChatMessage.toFriendid];
    //隐藏小红点
    [self.pointView setHidden:YES];
}

- (void)setPlayerStatus:(BOOL)playerStatus {
    
    if(playerStatus) {

        [self startVoiceAnimation];
        
    }else {
        
        [self stopVoiceAnimation];
    }
}

- (void)clickCell {
    ChatMessage *voiceMsg = self.ChatMessage;
    NSString *path =  LocalVoicePath(voiceMsg.toFriendid, voiceMsg.contentPath);
    Log(@"play path is %@",path);
    //发的语音或者收的下载成功的语音可以点击
    if (voiceMsg.mediaStatus == MEDIA_DOWNLOAD_SUCC || voiceMsg.msgSourceType == CHAT_MSG_SEND) {
        if (self.playerStatus) {
            self.playerStatus  = NO;
            [[VoiceChatModule getInstance] stopPlayAudio];
        }else {
            self.playerStatus = YES;
            [[VoiceChatModule getInstance] startPlayAudio:path];
            [NSNotificationCenter postOneVoiceCellPlayerNotification:@{@"msgId":self.ChatMessage.msgId}];
        }
    }else {
        //收的语音消息有下载状态，没有下载成功的点击继续下载
        if (voiceMsg.mediaStatus==MEDIA_DOWNLOAD_FAIL || voiceMsg.mediaStatus==MEDIA_DOWNLOAD_NONE ) {
#warning 语音下载暂时未做
            
            voiceMsg.mediaStatus = MEDIA_DOWNLOADING;
        }
        
    }
}



//功能待定
- (void)showMenuControllerInView:(ChatTableViewVoiceCell *)inView
                          bgView:(UIView *)supView {
    
    self.coversImageView.hidden=NO;
    
    [self becomeFirstResponder];
    
    UIMenuItem *copyTextItem1 = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(copyTextSender1)];
    
    UIMenuController *menu = [UIMenuController sharedMenuController];
    [menu setTargetRect:supView.frame inView:inView];
    [menu setArrowDirection:UIMenuControllerArrowDefault];
    [menu setMenuItems:@[copyTextItem1]];
    
    [menu setMenuVisible:YES animated:YES];
}

#pragma mark 剪切板代理方法
- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    
    if (action == @selector(copyTextSender1)) {
        return true;
    }else {
        return false;
    }
}

//删除
- (void)copyTextSender1 {
    
    !self.removeChatInfoBlock?:self.removeChatInfoBlock(self.ChatMessage);
}

#pragma mark - 通知
- (void)oneVoiceCellPlayer:(NSNotification *)not {
    NSDictionary *userInfo = not.userInfo;
    NSString *msgid = userInfo[@"msgId"];
    if (![msgid isEqualToString:self.ChatMessage.msgId]) {
        self.playerStatus = NO;
    }
}
- (void)audioPlayerDone:(NSNotification *)not {
    self.playerStatus = NO;
}

@end
